package com.guoxin.mashibing;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class MyContainer2 {

    volatile List<Object> list = new ArrayList<>();

    public void add(Object o) {
        list.add(o);
    }

    public int getSize() {
        return list.size();
    }

    public static void main(String[] args) {
        MyContainer2 container = new MyContainer2();
        final CountDownLatch latch = new CountDownLatch(1);

        Thread t1 = new Thread("T1") {
            @Override
            public void run() {
                System.out.println("T1 is start");
                synchronized (latch) {
                    for (int i = 0; i < 10; i++) {
                        if (i == 5) {
                            latch.countDown();
                        }
                        System.out.println(Thread.currentThread().getName() + " >> " + i);
                        container.add(i);
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("T1 is end");
                }
            }
        };

        Thread t2 = new Thread("T2") {
            @Override
            public void run() {
                System.out.println("T2 is start");
                if (container.getSize() != 5) {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("T2 is end");
            }
        };
        t1.start();
        t2.start();

    }
}
